<?php
class Films_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * 	GUARDA LA INFORMACION DE UNA PELICULA
	 * 
	 * 	@param	array $params					Parametros POST enviados
	 * 	
	 *  @return array
	 */
	public function saveInfoFilm($params){
		
		//	VALIDA SI ES $PARAMS ES UN ARRAY
		if(is_array($params)){
			
			//	CARGA LAS LIBRERIAS NECESARIAS
			$this->load->model('user_model');
			// $this->load->library('uploadfiles');
			$this->load->library('imageshack');
			
			//	OBTIENE EL ID DEL USUARIO QUE AGREGO LA PELICULA
			$res	= $this->user_model->getIdUserToken($params);
			$user	= $res->row_array();
			
			//	OBTIENE ARRAY CON LAS URLS DE LOS TAMAÑOS BIG - MEDIUM - SMALL
			$res_img_poster	= $this->getPosterUrl($params, 'poster', array('big','medium','small'));
			
			$URLb = $res_img_poster['big'];
			$URLm = $res_img_poster['medium'];
			$URLs = $res_img_poster['small'];
			
			// $URLb	= $res_img_poster['big']['url'];
			// $URLm	= $res_img_poster['medium']['url'];
			// $URLs	= $res_img_poster['small']['url'];

			//	ARRAY QUE CONTIENE LOS DATOS DE LA PELICULA A INSERTAR 
			$data	= array(
							'id_usuarios'		=> $user['id_usuario'],
							'titulo'			=> $params['title'],
							'titulo_limpio'		=> Sys::toAscii($params['title']),
							'url_poster_big'	=> $URLb,
							'url_poster_medium'	=> $URLm,
							'url_poster_small'	=> $URLs,
							'fecha_add'			=> date('Y-m-d H:i:s'),
					);
			
			//	SI EXISTE ALGUNO DE LOS SIGUIENTES PARAMETROS ES AGREGADO AL ARRAY $DATA.
			if(isset($params['coming_soon'])) 	$data['prox_estreno'] 	= $params['coming_soon'];
			if(isset($params['date_release'])) 	$data['anio'] 			= $params['date_release'];
			// if(isset($params['languaje']))		$data['idioma'] 		= $params['languaje'];
			// if(isset($params['subtitle']))		$data['subtitulos'] 	= $params['subtitle'];
			// if(isset($params['format_film'])) 	$data['formato'] 		= $params['format_film'];
			// if(isset($params['quality'])) 		$data['calidad'] 		= $params['quality'];
			// if(isset($params['duration'])) 		$data['duracion'] 		= $params['duration'];
			// if(isset($params['size'])) 			$data['tamanio'] 		= $params['size'];
			if(isset($params['synopsis_spa']))	$data['sinopsis_spa']	= $params['synopsis_spa'];
			if(isset($params['synopsis_eng']))	$data['sinopsis_eng'] 	= $params['synopsis_eng'];
			if(isset($params['trailers']))		$data['trailer'] 		= $params['trailers'];
			// if(isset($params['id_facebook']))	$data['id_facebook']	= $params['id_facebook'];

			//	INSERTA EL ARRAY $DATA
			$this->db->insert('peliculas',$data);
			//	OBTIENE EL ID DEL INSERT
			$id_film	= $this->db->insert_id();
			
			//	SI EXISTEN CAPTURAS, GUARDA LA(S) IMAGEN(ES) EN IMAGESHACK, OBTIENE LA URL Y CONSTRUYE EL ARRAY $DATA_SCREEN CON LOS VALORES RECIBIDOS Y LOS INSERTA
			// if(isset($_FILES['screenshots']) || isset($params['screenshots'])){
				// $url_screen	= $this->getScreenshotUrl($params, 'screenshots', '1280x0');
				// if(is_array($url_screen)){
					// $data_screen	= array('id_pelicula' => $id_film, 'url_captura' => $url_screen['1280x0'], 'primaria' => 1);
					// // $data_screen	= array('id_pelicula' => $id_film, 'url_captura' => $url_screen['1280x0']['url'], 'primaria' => 1);
					// $this->db->insert('peliculas_capturas',$data_screen);
				// }
			// }
			
			//	SI EXISTEN CATEGORIAS, CONSTRUYE EL ARRAY $DATA_CATEGORIES CON LOS VALORES RECIBIDOS Y LOS INSERTA.
			if(isset($params['categories'])){
				$data_categories	= $this->buildCategoriesArray($params, $id_film);
				// var_dump($data_categories);
				$this->db->insert_batch('peliculas_categorias',$data_categories);
			}
			
			//	SI EXISTEN CASTS, CONSTRUYE EL ARRAY $DATA_CAST CON LOS VALORES RECIBIDOS Y LOS INSERTA.
			if(isset($params['cast'])){
				$data_cast	= $this->buildCastArray($params,$id_film);
				// var_dump($data_cast);
				$this->db->insert_batch('peliculas_reparto',$data_cast);
			}
			
			//	SI EXISTEN SERVERS Y SOURCES, CONSTRUYE EL ARRAY $DATA_SERVERS_URLS CON LOS VALORES RECIBIDOS Y LOS INSERTA.
			// if(isset($params['servers']) && isset($params['sources']) && isset($params['online'])){
				// $data_servers_urls	= $this->buildServersUrlsArray($params,$id_film);
				// // var_dump($data_servers_urls);
				// $this->db->insert_batch('peliculas_fuentes',$data_servers_urls);
			// }
			
			if(isset($params['on_fb']))
				if($params['on_fb']==1){
					$this->load->library('my_facebook');
					$this->my_facebook->_makePost('films',$id_film);
				}
			
			//	REGRESA ARRAY CON EL PARAMETRO ID_PELICULA
			return array('id_pelicula' => $id_film);
		}
	}

	/**
	 * 	ACTUALIZA LA INFORMACION DE UNA PELICULA
	 * 
	 * 	@param	array $params					Parametros POST enviados
	 * 
	 * 	@return mixed
	 */
	public function updateInfoFilm($params){
		
		//	VALIDA QUE EXISTA LA PELICUA A ACTUALIZAR
		if($this->exist('peliculas', array('id_pelicula'=>$params['id_film']))){
			
			//	CARGA LAS LIBRERIAS NECESARIAS
			// $this->load->library('uploadfiles');
			$this->load->library('imageshack');
			
			//	ARRAY QUE CONTIENE LOS DATOS A INSERTAR DE LA PELICULA
			$data	= array(
							'titulo'		=> $params['title'],
							'fecha'			=> date("Y-m-d H:i:s")
							// 'titulo_limpio'		=> Sys::toAscii($params['title']),
					);

			//	SI EXISTE ALGUNO DE LOS SIGUIENTES PARAMETROS ES AGREGADO AL ARRAY $DATA.

			if (isset($_FILES['poster']) || isset($params['poster'])) {
				$res_img_poster	= $this->getPosterUrl($params, 'poster', array('big','medium','small'));
				if(is_array($res_img_poster)){
					$URLb = $res_img_poster['big'];
					$URLm = $res_img_poster['medium'];
					$URLs = $res_img_poster['small'];
	
					// $URLb	= $res_img_poster['big']['url'];
					// $URLm	= $res_img_poster['medium']['url'];
					// $URLs	= $res_img_poster['small']['url'];
					
					$data['url_poster_big']		= $URLb;
					$data['url_poster_medium']	= $URLm;
					$data['url_poster_small']	= $URLs;
				}
			}
			
			if(isset($params['coming_soon'])) 	$data['prox_estreno'] 	= $params['coming_soon'];
			if(isset($params['date_release'])) 	$data['anio'] 			= $params['date_release'];
			if(isset($params['languaje']))		$data['idioma'] 		= $params['languaje'];
			if(isset($params['subtitle']))		$data['subtitulos'] 	= $params['subtitle'];
			if(isset($params['format_film'])) 	$data['formato'] 		= $params['format_film'];
			if(isset($params['quality'])) 		$data['calidad'] 		= $params['quality'];
			if(isset($params['duration'])) 		$data['duracion'] 		= $params['duration'];
			if(isset($params['size'])) 			$data['tamanio'] 		= $params['size'];
			if(isset($params['synopsis_spa']))	$data['sinopsis_spa']	= $params['synopsis_spa'];
			if(isset($params['synopsis_eng']))	$data['sinopsis_eng'] 	= $params['synopsis_eng'];
			if(isset($params['trailers']))		$data['trailer'] 		= $params['trailers'];			

			//	ACTUALIZA LA PELICULA CON LOS DATOS DEL ARRAY $DATA
			$this->db->where('id_pelicula',$params['id_film']);
			$this->db->update('peliculas',$data);
			
			$id_film = $params['id_film'];
			
			//	SI EXISTEN SCREENSHOTS LOS ACTUALIZA
			if (isset($_FILES['screenshots']) || isset($params['screenshots'])){
				$url_screen	= $this->getScreenshotUrl($params, 'screenshots', '1280x0');
				
				if(is_array($url_screen)){
					$data_screen	= array('id_pelicula' => $id_film, 'url_captura' => $url_screen['1280x0'], 'primaria' => 1);
					// $data_screen	= array('id_pelicula' => $id_film, 'url_captura' => $url_screen['1280x0']['url'], 'primaria' => 1);
					
					if ($this->exist('peliculas_capturas', array('id_pelicula'=>$params['id_film']))) {
						$this->db->where('id_pelicula',$params['id_film']);
						$this->db->update('peliculas_capturas ',array('primaria '=>0));
					}
					
					$this->db->insert('peliculas_capturas',$data_screen);
				}
			}
			
			//	SI EXISTEN CATEGORIAS LAS ACTUALIZA
			if (isset($params['categories'])) {
				$data_categories	= $this->buildCategoriesArray($params, $id_film);
				// var_dump($data_categories);
				if ($this->exist('peliculas_categorias', array('id_pelicula'=>$params['id_film']))) {
					$this->db->delete('peliculas_categorias', array('id_pelicula' => $params['id_film'])); 
				}
				$this->db->insert_batch('peliculas_categorias',$data_categories);
			}
			
			//	SI EXISTEN CASTS LOS ACTUALIZA
			if(isset($params['cast'])){
				$data_cast	= $this->buildCastArray($params,$id_film);
				// var_dump($data_cast);
				if ($this->exist('peliculas_reparto', array('id_pelicula'=>$params['id_film']))) {
					$this->db->delete('peliculas_reparto', array('id_pelicula' => $params['id_film'])); 
				}
				$this->db->insert_batch('peliculas_reparto',$data_cast);
			}
			
			//	SI EXISTEN SERVERS Y SOURCES LOS ACTUALIZA
			if(isset($params['servers']) && isset($params['sources']) && isset($params['online'])){
				$data_servers_urls	= $this->buildServersUrlsArray($params,$id_film);
				// var_dump($data_servers_urls);
				if ($this->exist('peliculas_fuentes', array('id_pelicula'=>$params['id_film']))) {
					$this->db->delete('peliculas_fuentes', array('id_pelicula' => $params['id_film'])); 
				}
				$this->db->insert_batch('peliculas_fuentes',$data_servers_urls);
			}
			
			if(isset($params['on_fb']))
				if($params['on_fb']==1){
					$this->load->library('my_facebook');
					$this->my_facebook->_makePost('films',$params['id_film']);
				}
			
			//	REGRESA ARRAY CON EL PARAMETRO ID_PELICULA
			return array('id_pelicula' => $params['id_film']);
			
		}
		//	REGRESA FALSE SI NO EXISTE LA PELICULA A ACTUALIZAR
		return FALSE;
	}

	/**
	 * 	OBTIENE TODA LA INFORMACION DE UNA PELICULA
	 * 
	 * 	@param array $params					Parametros POST enviados
	 * 
	 *	@return mixed
	 */
	public function getInfoFilm($params){
		
		//	VALIDA QUE EXISTA LA PELICULA
		if ($this->exist('peliculas', array('id_pelicula'=>$params['id_film']))) {
			
			//	VARIABLES QUE INDICAN SI EXISTEN SCREENSHOTS, CATEGORIAS, CAST , SERVERS Y SOURCES PARA LA PELICULA
			$isScreenshots	= FALSE;
			$isCategories	= FALSE;
			$isCast			= FALSE;
			$isServerSource = FALSE;
			
			$this->db->query('SET GROUP_CONCAT_MAX_LEN=65535;');
			
			//p.url_poster_big as poster_big, p.url_poster_medium as poster_medium, p.url_poster_small as poster_small,
			
			//	STRING QUE CONTIENE LOS CAMPOS PARA LA CONSULTA
			$fields	= "
					   p.id_pelicula as id_film, 
					   p.titulo as title, 
					   p.titulo_limpio as clean_title, 
					   p.anio as date_release,
					   p.sinopsis_spa as synopsis_spa, 
					   p.sinopsis_eng as synopsis_eng,
					   posters.posters,
					   p.trailer as trailers, 
					   p.ranking,
					   get_votes(p.id_pelicula, (SELECT 'f')) AS votes,
					   u.nombre AS posted_by,
					   DATE(p.fecha) as last_update, 
					   DATE(p.fecha_add) as date, 
					   p.prox_estreno as coming_soon, 
					   p.id_facebook";
			
			// VALIDA QUE EXISTAN CAPTURAS 
			if ($this->exist('peliculas_capturas', array('id_pelicula'=>$params['id_film']))){
				$isScreenshots = TRUE;
				//	CONCATENA CAMPO AL STRING $FIELDS
				$fields	.= ',pcap.url_captura as screenshots';
			}
				
			// VALIDA QUE EXISTAN CATEGORIAS 
			if ($this->exist('peliculas_categorias', array('id_pelicula'=>$params['id_film']))){
				$isCategories	= TRUE;
				//	CONCATENA CAMPO AL STRING $FIELDS
				$fields	.= ', pcat.categorias as categories';
			}
			
			// VALIDA QUE EXISTAN CAST 
			if ($this->exist('peliculas_reparto', array('id_pelicula'=>$params['id_film']))){
				$isCast	= TRUE;
				//	CONCATENA CAMPO AL STRING $FIELDS
				$fields	.= ', prep.cast';
			}
			
			// VALIDA QUE EXISTAN SERVER Y SOURCES
			if ($this->exist('peliculas_fuentes', array('id_pelicula'=>$params['id_film']))){
				$isServerSource	= TRUE;
				//	CONCATENA CAMPO AL STRING $FIELDS
				$fields	.= ', pfuentes.fuentes as sources';
			}
			
			//	EMPIEZA A CONTRUIR QUERY
			$this->db->select($fields)->from('peliculas as p')
			->join('usuarios AS u', 'u.id_usuarios = p.id_usuarios' , 'inner');
			
			// p.url_poster_big as poster_big, p.url_poster_medium as poster_medium, p.url_poster_small as poster_small,
			$this->db->join('(
									SELECT
									CONCAT("[", 
												GROUP_CONCAT(
													CONCAT("{\"big\":\"",url_poster_big,"\""),
													CONCAT(",\"medium\":\"",url_poster_medium,"\""),
													CONCAT(",\"small\":\"",url_poster_small,"\"}")
												),
										  "]")
									as posters, id_pelicula 
									FROM peliculas
									WHERE id_pelicula = '.$params['id_film'].') as posters'
									, 
									'p.id_pelicula = p.id_pelicula' , 'inner'
								 );
			
			//	SI EXISTE SCREENSHOTS AGREGA EL JOIN AL QUERY
			if ($isScreenshots)
				$this->db->join('(
									SELECT
									CONCAT("[", 
												GROUP_CONCAT(
													CONCAT("{\"url\":\"",pcap.url_captura,"\""),
													CONCAT(",\"primary\":\"",pcap.primaria,"\"}")
												),
										  "]")
									as url_captura, id_pelicula 
									FROM peliculas_capturas as pcap
									WHERE id_pelicula = '.$params['id_film'].') as pcap'
									, 
									'pcap.id_pelicula = p.id_pelicula' , 'inner'
								 );
				// $this->db->join('peliculas_capturas as pcap', 'pcap.id_pelicula = p.id_pelicula', 'inner');
			
			//	SI EXISTE CATEGORIAS AGREGA EL JOIN AL QUERY
			if ($isCategories)
				$this->db->join('(
									SELECT
									CONCAT("[", 
												GROUP_CONCAT(
													CONCAT("{\"id\":",cat.id_categoria),
													CONCAT(",\"name\":\"",cat.nombre,"\"}")
												),
										  "]")
									as categorias, pcat.id_pelicula 
									FROM categorias as cat 
									INNER JOIN peliculas_categorias as pcat 
									ON cat.id_categoria = pcat.id_categoria
									WHERE cat.calidad = 0 AND pcat.id_pelicula = '.$params['id_film'].') as pcat'
									, 
									'pcat.id_pelicula = p.id_pelicula', 'inner'
								 );
								 
			//	SI EXISTE CAST AGREGA EL JOIN AL QUERY
			if ($isCast)
				$this->db->join('(
									SELECT 
									CONCAT("[", 
												GROUP_CONCAT(
													CONCAT("{\"id\":",act.id_actor),
													CONCAT(",\"name\":\"",act.nombre,"\"}")
												),
										  "]")
									as cast, prep.id_pelicula
									FROM actores as act
									INNER JOIN peliculas_reparto as prep
									ON act.id_actor = prep.id_actor
									WHERE prep.id_pelicula = '.$params['id_film'].') as prep'
									,
									' prep.id_pelicula = p.id_pelicula', 'inner');
			
			//	SI EXISTEN SERVERS Y SOURCES AGREGA EL JOIN AL QUERY
			if ($isServerSource)
				$this->db->join ('(
									SELECT 
									CONCAT("[", 
												GROUP_CONCAT(
													CONCAT("{\"id_source\":",pfuentes.id_phash),
													CONCAT(",\"id\":\"",serv.id_servidor,"\""),
													CONCAT(",\"name\":\"",serv.nombre,"\""),
													CONCAT(",\"online1\":\"",serv.online,"\""),
													CONCAT(",\"online_pelim\":\"",serv.online_pelim,"\""),
													CONCAT(",\"online\":\"", pfuentes.online ,"\""),
													CONCAT(",\"image\":\"", serv.url_img ,"\""),
													CONCAT(",\"short\":\"", pfuentes.fuente ,"\""),
													CONCAT(",\"origen\":\"",pfuentes.fuente_origen,"\""),
													CONCAT(",\"language\":\"",IFNULL(pfuentes.idioma,""),"\""),
												    CONCAT(",\"subtitle\":\"",IFNULL(pfuentes.subtitulos,""),"\""), 
												    CONCAT(",\"format_film\":\"",IFNULL(pfuentes.formato,""),"\""),
												    CONCAT(",\"quality\":\"",IFNULL((SELECT nombre FROM categorias WHERE id_categoria = pfuentes.calidad),""),"\""), 
												    CONCAT(",\"duration\":\"",IFNULL(pfuentes.duracion,""),"\""), 
												    CONCAT(",\"size\":\"",IFNULL(pfuentes.tamanio,""),"\""),
												    CONCAT(",\"url_subtitle\":\"",IFNULL(pfuentes.url_subtitulos,""),"\""),
												    CONCAT(",\"votes_pos\":\"",IFNULL(pfv.positivo, 0),"\""),
												    CONCAT(",\"votes_neg\":\"",IFNULL(pfv.negativo, 0),"\""),
													CONCAT(",\"user\":\"",IFNULL(IF(usu.usuario="",usu.nombre,usu.usuario),""),"\"}")
												),
										  "]")
									as fuentes, pfuentes.id_pelicula
									FROM servidores as serv
									INNER JOIN peliculas_fuentes as pfuentes
										ON serv.id_servidor = pfuentes.id_servidor
									LEFT JOIN usuarios as usu
										ON usu.id_usuarios = pfuentes.id_usuario
									LEFT JOIN (
										SELECT `id_phash`, Sum(positivo) AS positivo, Sum(negativo) AS negativo FROM `peliculas_fuentes_votos` GROUP BY id_phash
									) as pfv
										ON pfv.id_phash = pfuentes.id_phash
									WHERE pfuentes.id_pelicula = '.$params['id_film'].') as pfuentes'
									,
									' pfuentes.id_pelicula = p.id_pelicula', 'inner');

			//	AGREGA CLAUSULA WHERE AL QUERY
			$this->db->where('p.id_pelicula', $params['id_film']);
			
			//	EJECUTA QUERY Y OBTIENE EL RESULTADO
			$query = $this->db->get();
			$result	= $query->row_array();
			
			
			// $result['clean_title'] = $result['id_film'].'-'.$result['clean_title'];
			$result["type"] = lang('txt_type_film');
			
			//	OBTIENE LOS POSTERS COMO ARRAY Y LOS ASIGNA A $RESULT['POSTERS']
			$array = json_decode($result['posters'],TRUE);
	 		$result['posters'] = $array;
			
			//	SI EXISTE SCREENSHOTS ENTRA, OBTIENE LAS CATEGORIAS COMO ARRAY Y LAS ASIGNA A $RESULT['CATEGORIES']
			if ($isScreenshots){
				$array = json_decode($result['screenshots'],TRUE);
	 			$result['screenshots'] = $array;
			} 
			
			//	SI EXISTE CATEGORIAS ENTRA, OBTIENE LAS CATEGORIAS COMO ARRAY Y LAS ASIGNA A $RESULT['CATEGORIES']
			if ($isCategories){
				$array = json_decode($result['categories'],TRUE);
	 			$result['categories'] = $array;
			} 
			
			//	SI EXISTE CAST ENTRA, OBTIENE LOS CAST COMO ARRAY Y LAS ASIGNA A $RESULT['CAST']
			if ($isCast){
				$array = json_decode($result['cast'],TRUE);
	 			$result['cast'] = $array;
				
			}
			
			//	SI EXISTEN SERVERS Y SOURCES ENTRA, OBTIENE LOS SOURCES COMO ARRAY Y LAS ASIGNA A $RESULT['SOURCES']
			if ($isServerSource){
				$array = json_decode($result['sources'],TRUE);
	 			$result['sources'] = $array;
			}
			
			//	REGRESA EL ARRAY CON TODOS LOS PARAMETROS DE $RESULT
			return array($result);
		}
		//	REGRESA FALSE SI NO EXISTE LA PELICULA
		return FALSE;
		
		
	}

	/**
	 * OBTIENE UN LISTADO DE PELICULAS DE LA API TMDB
	 * 
	 * @param array $params					Parametros POST enviados
	 * 
	 * @return mixed
	 */
	public function getMoviesListTmdb($params){
		
		$this->load->library('tmdb');
		
		$movie_name	= $params['name_movie'].(isset($params['year']) ? ' '.$params['year'] : '');
		
		$result		= $this->tmdb->searchMovie($movie_name);
		$result 	= json_decode($result);
		
		if(is_array($result) && $result[0]!=='Nothing found.'){
			
			foreach ($result as $array) {
				
				$url_poster = '';
				if(isset($array->posters)){
					foreach ($array->posters as $poster) {
						if($poster->image->size == 'w154'){
							$url_poster	= $poster->image->url;
							break;
						}
					}
				}
				
				$movie_list['movie_list'][] = array(
				
												'original_name' => $array->original_name,
												'tmdb_id'		=> $array->id,
												'imdb_id'		=> $array->imdb_id,
												'released'		=> $array->released,
												'url_poster'	=> $url_poster
				
										); 
			}
				
			return $movie_list;
		}
		else return array('list' => lang('txt_search_movie_tmdb'));
	}
	
	/**
	 * OBTIENE LA INFORMACION DE UNA PELICULA DE LA API TMDB
	 * 
	 * @param array $params					Parametros POST enviados
	 * 
	 * @return mixed
	 * 
	 */
	public function getInfoMovieTmdb($params){
			
		$this->load->library('tmdb');
		
		$str_field_sinop = 'synopsis_en';
		if(isset($params['idiom'])){
			$this->tmdb->setLang($params['idiom']);
			$str_field_sinop = 'synopsis_'.$params['idiom'];
		}
		
		$result	= $this->tmdb->getMovie($params['id_tmdb']);
		$result	= json_decode($result);
		
		// var_dump($result);exit;
		if (is_array($result)) {
				
			$url_poster 	= '';
			$array_genres	= array();
			$array_cast		= array();
			
			if(isset($result[0]->genres) && count($result[0]->genres)>0){
				foreach ($result[0]->genres as $genres) {
					$array_genres[]	= $genres->name;
				}
			}
			
			if(isset($result[0]->posters) && count($result[0]->posters)>0){
				foreach ($result[0]->posters as $poster) {
					if($poster->image->size == 'mid'){
						$url_poster	= $poster->image->url;
						break;
					}
				}
			}
			
			if(isset($result[0]->cast) && count($result[0]->cast)>0){
				foreach ($result[0]->cast as $cast) {
					if($cast->job == 'Actor'){
						$array_cast[]	= $cast->name;
					}
				}
			}
			
			$array_genres	= $this->tvdbGetCategories($array_genres);
			$array_cast		= $this->tvdbGetCast($array_cast);
			
			$info_movie['movie_info'] = array(
												'title' 			=> isset($result[0]->original_name) ? $result[0]->original_name : '',
												'poster'			=> isset($url_poster) ? $url_poster : '',
												'date_release'		=> isset($result[0]->released) ? $result[0]->released : '',
												$str_field_sinop	=> isset($result[0]->overview) ? $result[0]->overview : '',
												'trailers'			=> isset($result[0]->trailer) ? $result[0]->trailer : '' ,
												'categories'		=> isset($array_genres) ? $array_genres : '',
												'cast'				=> isset($array_cast) ? $array_cast : ''
										);
			
			// $info_movie['info_movie']	= $result;
			
			return $info_movie;

		}
		else return array('info_movie' => lang('txt_search_movie_tmdb'));
		
	}

	/**
	 * 	GETTER QUE REALIZA UN UPLOAD A IMAGESHACK Y OBTIENE LAS URL DE LOS POSTERS
	 * 
	 * 	@param	array 	$params					Parametros POST enviados
	 * 	@param	string 	$name_field				Nombre del $_FILE o $_POST
	 * 	@param	array	$size					Tamaño al que sera redimensionada la imagen
	 * 
	 * 	@return	array
	 */
	private function getPosterUrl($params,$name_field,$size){
		//	SI LLEGAN LOS PARAMETROS $_FILES['POSTER'] Y $PARAMS['POSTER'] DA LA PRIORIDAD A $_FILES['POSTER'].
		//	SI LLEGA UNICAMENTE  $_FILES['POSTER'] ENTRA.
		$bool = FALSE;
		if((isset($_FILES[$name_field]) && isset($params[$name_field])) || isset($_FILES[$name_field])){
			if(!empty($_FILES[$name_field]['name'])){
				$conf_img_poster = array(
						'file' 		=> $name_field,
						'img_temp' 	=> TRUE,
						'size' 		=> $size
					); 
				$bool=TRUE;
			}
			else if(!empty($params[$name_field])){
				$conf_img_poster = array(
					'file' 		=> $params[$name_field],
					'img_temp' 	=> FALSE,
					'size' 		=> $size
				);
				$bool=TRUE;
			}
		}
		else{
			$conf_img_poster = array(
					'file' 		=> $params[$name_field],
					'img_temp' 	=> FALSE,
					'size' 		=> $size
				);
			$bool=TRUE;
		}
		
		//	OBTIENE LAS URLS QUE LE PERTENCE A CADA UNO DE LOS TAMAÑOS DE LA IMAGEN.
		if($bool){
			
			$this->imageshack->upload($conf_img_poster);
			return array(
					'big'		=> $this->imageshack->getInfo('image_link', 'big'),
					'medium'	=> $this->imageshack->getInfo('image_link', 'medium'),
					'small'		=> $this->imageshack->getInfo('image_link', 'small'),
				);
			
			// $res_img_poster	= $this->uploadfiles->uploadFile($conf_img_poster);
			// return $res_img_poster;
		}
		else return FALSE;
		
	}


	/**
	 * 	GETTER QUE REALIZA UN UPLOAD A IMAGESHACK Y OBTIENE LAS URL DE LOS SCREENSHOT
	 *
	 * 	@param	string 	$name_field				Nombre del $_FILE o $_POST
	 * 	@param	array	$size					Tamaño al que sera redimensionada la imagen
	 * 
	 * 	@return	array
	 */
	private function getScreenshotUrl($params, $name_field, $size){		
		$bool = FALSE;
		if((isset($_FILES[$name_field]) && isset($params[$name_field])) || isset($_FILES[$name_field])){
			if(!empty($_FILES[$name_field]['name'])){
				$conf_img_screen = array(
						'file' 		=> $name_field,
						'img_temp' 	=> TRUE,
						'size' 		=> array($size)
					); 
				$bool=TRUE;
			}
			else if(!empty($params[$name_field])){
				$conf_img_screen = array(
					'file' 		=> $params[$name_field],
					'img_temp' 	=> FALSE,
					'size' 		=> array($size)
				);
				$bool=TRUE;
			}
		}
		else{
			$conf_img_screen = array(
					'file' 		=> $params[$name_field],
					'img_temp' 	=> FALSE,
					'size' 		=> array($size)
				);
			$bool=TRUE;
		}

		if($bool){
			
			$this->imageshack->upload($conf_img_screen);
			return array($size => $this->imageshack->getInfo('image_link', '1280x0'));
			
			// $res_img_screen	= $this->uploadfiles->uploadFile($conf_img_screen);		
			// return $res_img_screen;
		}
		else return FALSE;
	}
	
	/**
	 * CONSTRUYE ARRAY CATEGORIAS
	 * 
	 * @param	array $params					Parametros POST enviado
	 * @param	int $id_film					Id de la Pelicula
	 * 
	 * @return array
	 */
	private function buildCategoriesArray($params,$id_film){
		foreach ($params['categories'] as $key => $itm)
			$data_categories[] = array(
										'id_pelicula'	=> $id_film, 
										'id_categoria'	=> $itm
									);
		return $data_categories;
	}

	/**
	 * CONSTRUYE ARRAY CAST
	 * 
	 * @param	array $params					Parametros POST enviado
	 * @param	int $id_film					Id de la Pelicula
	 * 
	 * @return array
	 */
	private function buildCastArray($params,$id_film){
		foreach ($params['cast'] as $key => $itm)
			$data_cast[] = array(
										'id_pelicula'	=> $id_film, 
										'id_actor'		=> $itm
									);
		return $data_cast;
	}
	
	/**
	 * CONSTRUYE ARRAY DE SERVIDORES Y URLS
	 * 
	 * @param	array $params					Parametros POST enviado
	 * @param	int $id_film					Id de la Pelicula
	 * 
	 * @return array
	 */
	private function buildServersUrlsArray($params,$id_film){
		
		$this->load->library('goo');
		
		foreach ($params['servers'] as $key => $itm) 
			$data_servers_urls[] = array(
										'id_servidor'	=> $itm, 
										'id_pelicula'	=> $id_film,
										'fuente'		=> $this->goo->shorten($params['sources'][$key]),
										'fuente_origen'	=> $params['sources'][$key],
										'online'		=> $params['online'][$key]
									);
		return $data_servers_urls;
	}
	
	
	
	/**
	 * Obtiene los actores de la serie, si no estan los inserta
	 */
	public function tvdbGetCast($actors=array()){
		$exist = '';
		$res_actors = array();
		foreach ($actors as $key => $value) {
			$value = Sys::limpiarTexto($value);
			
			$exist = $this->exist('actores', array('nombre' => $value), true);
			if(is_object($exist)){ //ya exite el actor
				$res_actors[] = array(
					'id' 	=> $exist->id_actor,
					'name' 	=> $exist->nombre
				);
			}else{  //no existe - Se inserta
				$this->db->insert('actores', array('nombre' => $value));
				$res_actors[] = array(
					'id' 	=> $this->db->insert_id(),
					'name' 	=> $value
				);
			}
		}
		
		return $res_actors;
	}
	
	/**
	 * Obtiene las categorias de la serie, si no esta las inserta
	 */
	public function tvdbGetCategories($categories=array()){
		$exist = '';
		$res_cate = array();
		foreach ($categories as $key => $value) {
			$value = Sys::limpiarTexto($value);
			
			$exist = $this->exist('categorias', array('nombre' => $value), true);
			if(is_object($exist)){ //ya exite la categoria
				$res_cate[] = array(
					'id' 	=> $exist->id_categoria,
					'name' 	=> $exist->nombre
				);
			}else{  //no existe - Se inserta
				$this->db->insert('categorias', array(
					'nombre' 		=> $value, 
					'nombre_limpio' => Sys::toAscii($value)
					)
				);
				$res_cate[] = array(
					'id' 	=> $this->db->insert_id(),
					'name' 	=> $value
				);
			}
		}
		
		return $res_cate;
	}
	
	
	
	
	/**
	 * Obtiene los actores de una pelicula
	 */
	public function getCast($id_film){
		$res_cast = $this->db
			->select('a.id_actor AS id, a.nombre AS name')
			->from('actores AS a')
				->join('peliculas_reparto AS pr', 'a.id_actor = pr.id_actor', 'inner')
			->where('pr.id_pelicula = '.$id_film)
			->order_by('a.nombre', 'ASC')
		->get();
		$cast = array();
		foreach ($res_cast->result_array() as $value) {
			$cast[] = $value;
		}
		return $cast;
	}
	
	/**
	 * Obtiene las categorias de una pelicula
	 */
	public function getCategories($id_film, $calidad=null){
		if($calidad==1) //solo categorias de tipo Calidad o ripeo
			$ssql = 'c.calidad = 1 AND ';
		elseif($calidad==0)
			$ssql = 'c.calidad = 0 AND ';
		
		$res_cate = $this->db
			->select('c.id_categoria AS id, c.nombre AS name')
			->from('categorias AS c')
				->join('peliculas_categorias AS pc', 'c.id_categoria = pc.id_categoria', 'inner')
			->where($ssql.'pc.id_pelicula = '.$id_film)
			->order_by('c.nombre', 'ASC')
		->get();
		$categories = array();
		foreach ($res_cate->result_array() as $value) {
			$categories[] = $value;
		}
		return $categories;
	}
	

	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}

}
